/**
 *****************************************************************************
 * DESC ：. 
 * Author : Junwei Zhang 
 * CREATEDATE ：2012-8-17 
 * MODIFYLIST ：       	Name 			 Date 			Reason/Contents
 * 				------------------------------------------------------ 
 * 				 	Junwei Zhang     2012-8-17		Created.
 ****************************************************************************
 **/
package com.me.server;

import java.io.File;
import java.io.FileWriter;

/**
 * 服务器端日志类. <br/>
 * 上午9:02:57 2012-8-17
 * 
 * @Author <a href="mailto:mestudying@sina.com">Junwei Zhang</a><br/>
 **/
public class Logger {
	/** 向控制台输出日志信息. */
	private static final int OUT_CONSOLE = 0;
	/** 向文件输出日志信息. */
	private static final int OUT_LOGFILE = 1;
	/** 日志输出方式:控制台 文件. */
	private int outputType = OUT_CONSOLE;
	/** 日志文件. */
	private File logFile = null;
	/** File Writer */
	private FileWriter logWriter = null;

	public Logger(String logFile) {
		// TODO Auto-generated constructor stub
		if (logFile == null) {
			this.outputType = OUT_CONSOLE;
			System.out.println("+ Write logs to STDOUT.");
		} else {
			this.outputType = OUT_LOGFILE;
			this.logFile = new File(logFile);
			if (this.logFile.canWrite()) {
				try {
					System.out.println("+ Write logs to: " + logFile);
					this.logWriter = new FileWriter(this.logFile);
					this.logWriter.write("\n-------------- + Start Logging at [" + "]. --------------\n");
					this.logWriter.flush();
				} catch (Exception e) {
					System.err.println("*** Can't write logs to: " + logFile + ". Exception: " + e.toString());
					this.logFile = null;
					this.outputType = OUT_CONSOLE;
					System.out.println("+ Writing logs to STDOUT.");
				}
			} else {
				System.err.println("*** Can't write logs to: " + logFile);
				this.logFile = null;
				this.outputType = OUT_CONSOLE;
				System.out.println("+ Writing logs to STDOUT.");
			}
		}
	}

	/**
	 * 输出日志信息.
	 * 
	 * @param output
	 *            输出的信息.
	 */
	public void write(String output) {
		// TODO Auto-generated method stub
		String tmpOutDate = new DateMan().getTime(0);
		if (this.outputType == Logger.OUT_CONSOLE) {
			System.out.println("[" + tmpOutDate + "]: " + output);
		} else if (this.outputType == Logger.OUT_LOGFILE) {
			try {
				this.logWriter.write("\n[" + tmpOutDate + "]: " + output);
				this.logWriter.flush();
			} catch (Exception e) {
			}
		}
	}

	/**
	 * 输出错误信息.
	 * 
	 * @param output
	 *            输出的信息.
	 */
	public void writeError(String output) {
		String tmpOutDate = "";
		if (this.outputType == Logger.OUT_CONSOLE) {
			System.err.println("[" + tmpOutDate + "] *** [ERROR]: " + output);
		} else if (this.outputType == Logger.OUT_LOGFILE) {
			try {
				this.logWriter.write("\n[" + tmpOutDate + "]: " + output);
				this.logWriter.flush();
			} catch (Exception e) {
			}
		}
	}

}
